"use client"

import { useState, useEffect } from "react"
import { useParams, useRouter } from "next/navigation"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Button } from "@/components/ui/button"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
import { 
  Shield, 
  Zap, 
  Thermometer, 
  ArrowLeft,
  Settings,
  Save,
  Upload,
  FileText,
  AlertTriangle,
  CheckCircle,
  Clock,
  RotateCcw
} from "lucide-react"
import { cn } from "@/lib/utils"

interface ProtectionSettings {
  stallProtection: string
  stallHoldTime: string
  stallRestartTime: string
  stallRestartCount: string
  overvoltageProtection: string
  overvoltageValue: string
  overvoltageRecoveryValue: string
  undervoltageProtection: string
  undervoltageValue: string
  undervoltageRecoveryValue: string
  temperatureProtection: string
  protectionTemp: string
  recoveryTemp: string
  overcurrentProtection: string
  overcurrentValue: string
  currentLimitProtection: string
  currentLimitValue: string
  blockageProtection: string
  blockageDiameter: string
  blockageHoldTime: string
  phaseProtection: string
}

interface Project {
  _id: string
  model: string
  PROJECT_CODE: string
  PROJECT_TYPE_NAME: string
}

export default function ProjectProtectionPage() {
  const params = useParams()
  const router = useRouter()
  const projectId = params.id as string
  
  const [project, setProject] = useState<Project | null>(null)
  const [protectionSettings, setProtectionSettings] = useState<ProtectionSettings>({
    stallProtection: "无",
    stallHoldTime: "",
    stallRestartTime: "",
    stallRestartCount: "",
    overvoltageProtection: "无",
    overvoltageValue: "",
    overvoltageRecoveryValue: "",
    undervoltageProtection: "无",
    undervoltageValue: "",
    undervoltageRecoveryValue: "",
    temperatureProtection: "无",
    protectionTemp: "",
    recoveryTemp: "",
    overcurrentProtection: "无",
    overcurrentValue: "",
    currentLimitProtection: "无",
    currentLimitValue: "",
    blockageProtection: "无",
    blockageDiameter: "",
    blockageHoldTime: "",
    phaseProtection: "无"
  })
  const [loading, setLoading] = useState(true)
  const [saving, setSaving] = useState(false)
  const [activeTab, setActiveTab] = useState("settings")

  useEffect(() => {
    loadProjectData()
  }, [projectId])

  const loadProjectData = async () => {
    try {
      setLoading(true)
      
      // 加载项目详情
      const response = await fetch(`/api/projects/${projectId}`)
      if (response.ok) {
        const projectData = await response.json()
        setProject(projectData)
        
        // 加载保护设置（模拟数据）
        setProtectionSettings({
          stallProtection: "有，自恢复",
          stallHoldTime: "1",
          stallRestartTime: "1",
          stallRestartCount: "3",
          overvoltageProtection: "有，自恢复",
          overvoltageValue: "27",
          overvoltageRecoveryValue: "25",
          undervoltageProtection: "有，自恢复",
          undervoltageValue: "18",
          undervoltageRecoveryValue: "19",
          temperatureProtection: "有，自恢复",
          protectionTemp: "100",
          recoveryTemp: "90",
          overcurrentProtection: "有，仅断电重启",
          overcurrentValue: "15",
          currentLimitProtection: "有",
          currentLimitValue: "12",
          blockageProtection: "有，自恢复",
          blockageDiameter: "3",
          blockageHoldTime: "5",
          phaseProtection: "有，仅断电重启"
        })
      }
    } catch (error) {
      console.error('加载项目数据失败:', error)
    } finally {
      setLoading(false)
    }
  }

  const handleSettingChange = (field: keyof ProtectionSettings, value: string) => {
    setProtectionSettings(prev => ({
      ...prev,
      [field]: value
    }))
  }

  const validateForm = () => {
    const newErrors: Record<string, string> = {}
    
    // 验证数值字段
    if (protectionSettings.stallProtection !== "无") {
      if (!protectionSettings.stallHoldTime) {
        newErrors.stallHoldTime = "堵转保持时间不能为空"
      }
      if (protectionSettings.stallProtection === "有，自恢复") {
        if (!protectionSettings.stallRestartTime) {
          newErrors.stallRestartTime = "堵转重启时间不能为空"
        }
        if (!protectionSettings.stallRestartCount) {
          newErrors.stallRestartCount = "堵转重启次数不能为空"
        }
      }
    }
    
    if (protectionSettings.overvoltageProtection !== "无") {
      if (!protectionSettings.overvoltageValue) {
        newErrors.overvoltageValue = "过压保护值不能为空"
      }
      if (protectionSettings.overvoltageProtection === "有，自恢复" && !protectionSettings.overvoltageRecoveryValue) {
        newErrors.overvoltageRecoveryValue = "过压恢复值不能为空"
      }
    }
    
    if (protectionSettings.undervoltageProtection !== "无") {
      if (!protectionSettings.undervoltageValue) {
        newErrors.undervoltageValue = "欠压保护值不能为空"
      }
      if (protectionSettings.undervoltageProtection === "有，自恢复" && !protectionSettings.undervoltageRecoveryValue) {
        newErrors.undervoltageRecoveryValue = "欠压恢复值不能为空"
      }
    }
    
    if (protectionSettings.temperatureProtection !== "无") {
      if (!protectionSettings.protectionTemp) {
        newErrors.protectionTemp = "保护温度不能为空"
      }
      if (protectionSettings.temperatureProtection === "有，自恢复" && !protectionSettings.recoveryTemp) {
        newErrors.recoveryTemp = "恢复温度不能为空"
      }
    }
    
    if (protectionSettings.overcurrentProtection !== "无" && !protectionSettings.overcurrentValue) {
      newErrors.overcurrentValue = "过流保护值不能为空"
    }
    
    if (protectionSettings.currentLimitProtection !== "无" && !protectionSettings.currentLimitValue) {
      newErrors.currentLimitValue = "限流值不能为空"
    }
    
    if (protectionSettings.blockageProtection !== "无") {
      if (!protectionSettings.blockageDiameter) {
        newErrors.blockageDiameter = "堵孔直径不能为空"
      }
      if (!protectionSettings.blockageHoldTime) {
        newErrors.blockageHoldTime = "堵孔保持时间不能为空"
      }
    }
    
    return newErrors
  }

  const handleSave = async () => {
    const errors = validateForm()
    if (Object.keys(errors).length > 0) {
      alert('请填写所有必填的保护参数')
      return
    }
    
    setSaving(true)
    try {
      const response = await fetch(`/api/projects/${projectId}/protection`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(protectionSettings)
      })

      if (response.ok) {
        // 显示保存成功消息
        alert('保护设置保存成功')
      } else {
        const error = await response.json()
        alert(`保存失败: ${error.error || '未知错误'}`)
      }
    } catch (error) {
      console.error('保存保护设置失败:', error)
      alert('保存失败，请重试')
    } finally {
      setSaving(false)
    }
  }

  const getProtectionStatus = (protectionType: string) => {
    const value = protectionSettings[protectionType as keyof ProtectionSettings]
    return value !== "无" && value !== ""
  }

  const getProtectionIcon = (enabled: boolean) => {
    return enabled ? CheckCircle : AlertTriangle
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center min-h-screen">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">加载保护设置中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 页面头部 */}
      <div className="bg-white shadow-sm border-b">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-6">
          <div className="flex items-center justify-between">
            <div className="flex items-center space-x-4">
              <Button variant="ghost" size="sm" onClick={() => router.back()}>
                <ArrowLeft className="h-4 w-4" />
              </Button>
              <div>
                <h1 className="text-2xl font-bold text-gray-900">电气保护设置</h1>
                <p className="text-sm text-gray-500">
                  {project?.model || '项目'} - {project?.PROJECT_CODE || '未编号'}
                </p>
              </div>
            </div>
            <div className="flex items-center space-x-2">
              <Button variant="outline" size="sm">
                <Upload className="h-4 w-4 mr-2" />
                导入配置
              </Button>
              <Button onClick={handleSave} disabled={saving}>
                <Save className="h-4 w-4 mr-2" />
                {saving ? '保存中...' : '保存设置'}
              </Button>
            </div>
          </div>
        </div>
      </div>

      {/* 主要内容 */}
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-6">
          <TabsList>
            <TabsTrigger value="settings">保护参数设置</TabsTrigger>
            <TabsTrigger value="summary">保护总览</TabsTrigger>
            <TabsTrigger value="testing">保护测试</TabsTrigger>
            <TabsTrigger value="history">修改历史</TabsTrigger>
          </TabsList>

          {/* 保护参数设置标签页 */}
          <TabsContent value="settings" className="space-y-6">
            <div className="grid grid-cols-1 gap-6">
              {/* 堵转保护 */}
              <Card className={cn(
                "border-l-4 transition-colors",
                getProtectionStatus("stallProtection") ? "border-l-green-500 bg-green-50" : "border-l-gray-300"
              )}>
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    {getProtectionIcon(getProtectionStatus("stallProtection"))({ 
                      className: cn("h-5 w-5", getProtectionStatus("stallProtection") ? "text-green-600" : "text-gray-400") 
                    })}
                    <Zap className="h-5 w-5 text-blue-600" />
                    <span>堵转保护</span>
                    <Badge variant={getProtectionStatus("stallProtection") ? "default" : "secondary"}>
                      {getProtectionStatus("stallProtection") ? "已启用" : "未启用"}
                    </Badge>
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                    <div className="space-y-2">
                      <Label>保护模式</Label>
                      <Select 
                        value={protectionSettings.stallProtection} 
                        onValueChange={(value) => handleSettingChange("stallProtection", value)}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="无">无</SelectItem>
                          <SelectItem value="有，自恢复">有，自恢复</SelectItem>
                          <SelectItem value="有，手动重开">有，手动重开</SelectItem>
                          <SelectItem value="有，仅断电重启">有，仅断电重启</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    
                    {protectionSettings.stallProtection !== "无" && (
                      <>
                        <div className="space-y-2">
                          <Label>保持时间 (S)</Label>
                          <Input
                            type="number"
                            value={protectionSettings.stallHoldTime}
                            onChange={(e) => handleSettingChange("stallHoldTime", e.target.value)}
                            placeholder="1"
                          />
                        </div>
                        
                        {protectionSettings.stallProtection === "有，自恢复" && (
                          <>
                            <div className="space-y-2">
                              <Label>重启时间 (S)</Label>
                              <Input
                                type="number"
                                value={protectionSettings.stallRestartTime}
                                onChange={(e) => handleSettingChange("stallRestartTime", e.target.value)}
                                placeholder="1"
                              />
                            </div>
                            
                            <div className="space-y-2">
                              <Label>重启次数 (次)</Label>
                              <Input
                                type="number"
                                value={protectionSettings.stallRestartCount}
                                onChange={(e) => handleSettingChange("stallRestartCount", e.target.value)}
                                placeholder="3"
                              />
                            </div>
                          </>
                        )}
                      </>
                    )}
                  </div>
                  
                  {protectionSettings.stallProtection !== "无" && (
                    <div className="mt-4 p-3 bg-blue-50 rounded-lg">
                      <p className="text-sm text-blue-800">
                        <strong>工作原理：</strong>
                        {protectionSettings.stallProtection === "有，自恢复" && 
                          `检测到堵转后保持 ${protectionSettings.stallHoldTime || 1}S，然后停机 ${protectionSettings.stallRestartTime || 1}S，尝试重启 ${protectionSettings.stallRestartCount || 3} 次`
                        }
                        {protectionSettings.stallProtection === "有，手动重开" && 
                          `检测到堵转后保持 ${protectionSettings.stallHoldTime || 1}S，然后停机，需要手动重启`
                        }
                        {protectionSettings.stallProtection === "有，仅断电重启" && 
                          `检测到堵转后立即断电，需要重新上电才能恢复`
                        }
                      </p>
                    </div>
                  )}
                </CardContent>
              </Card>

              {/* 过压保护 */}
              <Card className={cn(
                "border-l-4 transition-colors",
                getProtectionStatus("overvoltageProtection") ? "border-l-green-500 bg-green-50" : "border-l-gray-300"
              )}>
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    {getProtectionIcon(getProtectionStatus("overvoltageProtection"))({ 
                      className: cn("h-5 w-5", getProtectionStatus("overvoltageProtection") ? "text-green-600" : "text-gray-400") 
                    })}
                    <Zap className="h-5 w-5 text-orange-600" />
                    <span>过压保护</span>
                    <Badge variant={getProtectionStatus("overvoltageProtection") ? "default" : "secondary"}>
                      {getProtectionStatus("overvoltageProtection") ? "已启用" : "未启用"}
                    </Badge>
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div className="space-y-2">
                      <Label>保护模式</Label>
                      <Select 
                        value={protectionSettings.overvoltageProtection} 
                        onValueChange={(value) => handleSettingChange("overvoltageProtection", value)}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="无">无</SelectItem>
                          <SelectItem value="有，自恢复">有，自恢复</SelectItem>
                          <SelectItem value="有，手动重开">有，手动重开</SelectItem>
                          <SelectItem value="有，仅断电重启">有，仅断电重启</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    
                    {protectionSettings.overvoltageProtection !== "无" && (
                      <>
                        <div className="space-y-2">
                          <Label>保护值 (V)</Label>
                          <Input
                            type="number"
                            step="0.1"
                            value={protectionSettings.overvoltageValue}
                            onChange={(e) => handleSettingChange("overvoltageValue", e.target.value)}
                            placeholder="27"
                          />
                        </div>
                        
                        {protectionSettings.overvoltageProtection === "有，自恢复" && (
                          <div className="space-y-2">
                            <Label>恢复值 (V)</Label>
                            <Input
                              type="number"
                              step="0.1"
                              value={protectionSettings.overvoltageRecoveryValue}
                              onChange={(e) => handleSettingChange("overvoltageRecoveryValue", e.target.value)}
                              placeholder="25"
                            />
                          </div>
                        )}
                      </>
                    )}
                  </div>
                </CardContent>
              </Card>

              {/* 欠压保护 */}
              <Card className={cn(
                "border-l-4 transition-colors",
                getProtectionStatus("undervoltageProtection") ? "border-l-green-500 bg-green-50" : "border-l-gray-300"
              )}>
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    {getProtectionIcon(getProtectionStatus("undervoltageProtection"))({ 
                      className: cn("h-5 w-5", getProtectionStatus("undervoltageProtection") ? "text-green-600" : "text-gray-400") 
                    })}
                    <Zap className="h-5 w-5 text-yellow-600" />
                    <span>欠压保护</span>
                    <Badge variant={getProtectionStatus("undervoltageProtection") ? "default" : "secondary"}>
                      {getProtectionStatus("undervoltageProtection") ? "已启用" : "未启用"}
                    </Badge>
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div className="space-y-2">
                      <Label>保护模式</Label>
                      <Select 
                        value={protectionSettings.undervoltageProtection} 
                        onValueChange={(value) => handleSettingChange("undervoltageProtection", value)}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="无">无</SelectItem>
                          <SelectItem value="有，自恢复">有，自恢复</SelectItem>
                          <SelectItem value="有，手动重开">有，手动重开</SelectItem>
                          <SelectItem value="有，仅断电重启">有，仅断电重启</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    
                    {protectionSettings.undervoltageProtection !== "无" && (
                      <>
                        <div className="space-y-2">
                          <Label>保护值 (V)</Label>
                          <Input
                            type="number"
                            step="0.1"
                            value={protectionSettings.undervoltageValue}
                            onChange={(e) => handleSettingChange("undervoltageValue", e.target.value)}
                            placeholder="18"
                          />
                        </div>
                        
                        {protectionSettings.undervoltageProtection === "有，自恢复" && (
                          <div className="space-y-2">
                            <Label>恢复值 (V)</Label>
                            <Input
                              type="number"
                              step="0.1"
                              value={protectionSettings.undervoltageRecoveryValue}
                              onChange={(e) => handleSettingChange("undervoltageRecoveryValue", e.target.value)}
                              placeholder="19"
                            />
                          </div>
                        )}
                      </>
                    )}
                  </div>
                </CardContent>
              </Card>

              {/* 温度保护 */}
              <Card className={cn(
                "border-l-4 transition-colors",
                getProtectionStatus("temperatureProtection") ? "border-l-green-500 bg-green-50" : "border-l-gray-300"
              )}>
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    {getProtectionIcon(getProtectionStatus("temperatureProtection"))({ 
                      className: cn("h-5 w-5", getProtectionStatus("temperatureProtection") ? "text-green-600" : "text-gray-400") 
                    })}
                    <Thermometer className="h-5 w-5 text-red-600" />
                    <span>温度保护</span>
                    <Badge variant={getProtectionStatus("temperatureProtection") ? "default" : "secondary"}>
                      {getProtectionStatus("temperatureProtection") ? "已启用" : "未启用"}
                    </Badge>
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div className="space-y-2">
                      <Label>保护模式</Label>
                      <Select 
                        value={protectionSettings.temperatureProtection} 
                        onValueChange={(value) => handleSettingChange("temperatureProtection", value)}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="无">无</SelectItem>
                          <SelectItem value="有，自恢复">有，自恢复</SelectItem>
                          <SelectItem value="有，手动重开">有，手动重开</SelectItem>
                          <SelectItem value="有，仅断电重启">有，仅断电重启</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    
                    {protectionSettings.temperatureProtection !== "无" && (
                      <>
                        <div className="space-y-2">
                          <Label>保护温度 (℃)</Label>
                          <Input
                            type="number"
                            value={protectionSettings.protectionTemp}
                            onChange={(e) => handleSettingChange("protectionTemp", e.target.value)}
                            placeholder="100"
                          />
                        </div>
                        
                        {protectionSettings.temperatureProtection === "有，自恢复" && (
                          <div className="space-y-2">
                            <Label>恢复温度 (℃)</Label>
                            <Input
                              type="number"
                              value={protectionSettings.recoveryTemp}
                              onChange={(e) => handleSettingChange("recoveryTemp", e.target.value)}
                              placeholder="90"
                            />
                          </div>
                        )}
                      </>
                    )}
                  </div>
                </CardContent>
              </Card>

              {/* 其他保护 */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                {/* 过流保护 */}
                <Card className={cn(
                  "border-l-4 transition-colors",
                  getProtectionStatus("overcurrentProtection") ? "border-l-green-500 bg-green-50" : "border-l-gray-300"
                )}>
                  <CardHeader>
                    <CardTitle className="flex items-center space-x-2">
                      {getProtectionIcon(getProtectionStatus("overcurrentProtection"))({ 
                        className: cn("h-5 w-5", getProtectionStatus("overcurrentProtection") ? "text-green-600" : "text-gray-400") 
                      })}
                      <Zap className="h-5 w-5 text-purple-600" />
                      <span className="text-sm">过流保护</span>
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-3">
                      <Select 
                        value={protectionSettings.overcurrentProtection} 
                        onValueChange={(value) => handleSettingChange("overcurrentProtection", value)}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="无">无</SelectItem>
                          <SelectItem value="有，自恢复">有，自恢复</SelectItem>
                          <SelectItem value="有，手动重开">有，手动重开</SelectItem>
                          <SelectItem value="有，仅断电重启">有，仅断电重启</SelectItem>
                        </SelectContent>
                      </Select>
                      
                      {protectionSettings.overcurrentProtection !== "无" && (
                        <div className="space-y-2">
                          <Label className="text-sm">保护值 (A)</Label>
                          <Input
                            type="number"
                            step="0.1"
                            value={protectionSettings.overcurrentValue}
                            onChange={(e) => handleSettingChange("overcurrentValue", e.target.value)}
                            placeholder="15"
                          />
                        </div>
                      )}
                    </div>
                  </CardContent>
                </Card>

                {/* 限流保护 */}
                <Card className={cn(
                  "border-l-4 transition-colors",
                  getProtectionStatus("currentLimitProtection") ? "border-l-green-500 bg-green-50" : "border-l-gray-300"
                )}>
                  <CardHeader>
                    <CardTitle className="flex items-center space-x-2">
                      {getProtectionIcon(getProtectionStatus("currentLimitProtection"))({ 
                        className: cn("h-5 w-5", getProtectionStatus("currentLimitProtection") ? "text-green-600" : "text-gray-400") 
                      })}
                      <Zap className="h-5 w-5 text-indigo-600" />
                      <span className="text-sm">限流保护</span>
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <div className="space-y-3">
                      <Select 
                        value={protectionSettings.currentLimitProtection} 
                        onValueChange={(value) => handleSettingChange("currentLimitProtection", value)}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="无">无</SelectItem>
                          <SelectItem value="有">有</SelectItem>
                        </SelectContent>
                      </Select>
                      
                      {protectionSettings.currentLimitProtection === "有" && (
                        <div className="space-y-2">
                          <Label className="text-sm">限流值 (A)</Label>
                          <Input
                            type="number"
                            step="0.1"
                            value={protectionSettings.currentLimitValue}
                            onChange={(e) => handleSettingChange("currentLimitValue", e.target.value)}
                            placeholder="12"
                          />
                        </div>
                      )}
                    </div>
                  </CardContent>
                </Card>

                {/* 缺相保护 */}
                <Card className={cn(
                  "border-l-4 transition-colors",
                  getProtectionStatus("phaseProtection") ? "border-l-green-500 bg-green-50" : "border-l-gray-300"
                )}>
                  <CardHeader>
                    <CardTitle className="flex items-center space-x-2">
                      {getProtectionIcon(getProtectionStatus("phaseProtection"))({ 
                        className: cn("h-5 w-5", getProtectionStatus("phaseProtection") ? "text-green-600" : "text-gray-400") 
                      })}
                      <AlertTriangle className="h-5 w-5 text-red-600" />
                      <span className="text-sm">缺相保护</span>
                    </CardTitle>
                  </CardHeader>
                  <CardContent>
                    <Select 
                      value={protectionSettings.phaseProtection} 
                      onValueChange={(value) => handleSettingChange("phaseProtection", value)}
                    >
                      <SelectTrigger>
                        <SelectValue />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value="无">无</SelectItem>
                        <SelectItem value="有，自恢复">有，自恢复</SelectItem>
                        <SelectItem value="有，手动重开">有，手动重开</SelectItem>
                        <SelectItem value="有，仅断电重启">有，仅断电重启</SelectItem>
                      </SelectContent>
                    </Select>
                  </CardContent>
                </Card>
              </div>

              {/* 堵孔/空转保护 */}
              <Card className={cn(
                "border-l-4 transition-colors",
                getProtectionStatus("blockageProtection") ? "border-l-green-500 bg-green-50" : "border-l-gray-300"
              )}>
                <CardHeader>
                  <CardTitle className="flex items-center space-x-2">
                    {getProtectionIcon(getProtectionStatus("blockageProtection"))({ 
                      className: cn("h-5 w-5", getProtectionStatus("blockageProtection") ? "text-green-600" : "text-gray-400") 
                    })}
                    <AlertTriangle className="h-5 w-5 text-orange-600" />
                    <span>堵孔/空转保护</span>
                    <Badge variant={getProtectionStatus("blockageProtection") ? "default" : "secondary"}>
                      {getProtectionStatus("blockageProtection") ? "已启用" : "未启用"}
                    </Badge>
                  </CardTitle>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                    <div className="space-y-2">
                      <Label>保护模式</Label>
                      <Select 
                        value={protectionSettings.blockageProtection} 
                        onValueChange={(value) => handleSettingChange("blockageProtection", value)}
                      >
                        <SelectTrigger>
                          <SelectValue />
                        </SelectTrigger>
                        <SelectContent>
                          <SelectItem value="无">无</SelectItem>
                          <SelectItem value="有，自恢复">有，自恢复</SelectItem>
                          <SelectItem value="有，手动重开">有，手动重开</SelectItem>
                          <SelectItem value="有，仅断电重启">有，仅断电重启</SelectItem>
                        </SelectContent>
                      </Select>
                    </div>
                    
                    {protectionSettings.blockageProtection !== "无" && (
                      <>
                        <div className="space-y-2">
                          <Label>堵孔孔径 (mm)</Label>
                          <Input
                            type="number"
                            step="0.1"
                            value={protectionSettings.blockageDiameter}
                            onChange={(e) => handleSettingChange("blockageDiameter", e.target.value)}
                            placeholder="3"
                          />
                        </div>
                        
                        <div className="space-y-2">
                          <Label>保持时间 (S)</Label>
                          <Input
                            type="number"
                            value={protectionSettings.blockageHoldTime}
                            onChange={(e) => handleSettingChange("blockageHoldTime", e.target.value)}
                            placeholder="5"
                          />
                        </div>
                      </>
                    )}
                  </div>
                </CardContent>
              </Card>
            </div>
          </TabsContent>

          {/* 保护总览标签页 */}
          <TabsContent value="summary">
            <Card>
              <CardHeader>
                <CardTitle>保护功能总览</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
                  {Object.entries(protectionSettings).filter(([key]) => 
                    key.includes("Protection") && key !== "currentLimitProtection"
                  ).map(([key, value]) => {
                    const enabled = value !== "无" && value !== ""
                    const Icon = getProtectionIcon(enabled)
                    const getName = (key: string) => {
                      const nameMap: Record<string, string> = {
                        stallProtection: "堵转保护",
                        overvoltageProtection: "过压保护",
                        undervoltageProtection: "欠压保护",
                        temperatureProtection: "温度保护",
                        overcurrentProtection: "过流保护",
                        blockageProtection: "堵孔/空转保护",
                        phaseProtection: "缺相保护"
                      }
                      return nameMap[key] || key
                    }
                    
                    return (
                      <div key={key} className="flex items-center space-x-3 p-3 border rounded-lg">
                        <Icon className={cn("h-5 w-5", enabled ? "text-green-600" : "text-gray-400")} />
                        <div className="flex-1">
                          <div className="font-medium">{getName(key)}</div>
                          <div className="text-sm text-gray-500">{enabled ? value : "未启用"}</div>
                        </div>
                        <Badge variant={enabled ? "default" : "secondary"}>
                          {enabled ? "启用" : "禁用"}
                        </Badge>
                      </div>
                    )
                  })}
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* 保护测试标签页 */}
          <TabsContent value="testing">
            <Card>
              <CardHeader>
                <CardTitle>保护功能测试</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="text-center py-8 text-gray-500">
                  <Settings className="h-12 w-12 mx-auto mb-4 text-gray-400" />
                  <p>保护功能测试模块开发中...</p>
                  <p className="text-sm mt-2">将提供各种保护功能的模拟测试界面</p>
                </div>
              </CardContent>
            </Card>
          </TabsContent>

          {/* 修改历史标签页 */}
          <TabsContent value="history">
            <Card>
              <CardHeader>
                <CardTitle>修改历史</CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-4">
                  <div className="flex items-start space-x-4 p-4 border-l-4 border-blue-500 bg-blue-50 rounded-r-lg">
                    <div className="flex-shrink-0">
                      <Clock className="h-5 w-5 text-blue-600" />
                    </div>
                    <div className="flex-1">
                      <div className="flex items-center justify-between">
                        <div className="font-medium text-blue-900">保护设置初始化</div>
                        <div className="text-sm text-blue-700">2024-01-05 09:00</div>
                      </div>
                      <div className="text-sm text-blue-700 mt-1">操作人: 系统管理员</div>
                      <div className="text-sm text-blue-600 mt-1">备注: 项目创建时初始化默认保护设置</div>
                    </div>
                  </div>
                  
                  <div className="flex items-start space-x-4 p-4 border-l-4 border-green-500 bg-green-50 rounded-r-lg">
                    <div className="flex-shrink-0">
                      <RotateCcw className="h-5 w-5 text-green-600" />
                    </div>
                    <div className="flex-1">
                      <div className="flex items-center justify-between">
                        <div className="font-medium text-green-900">保护设置更新</div>
                        <div className="text-sm text-green-700">2024-01-15 14:30</div>
                      </div>
                      <div className="text-sm text-green-700 mt-1">操作人: 张工程师</div>
                      <div className="text-sm text-green-600 mt-1">备注: 根据客户需求调整堵转保护参数</div>
                    </div>
                  </div>
                </div>
              </CardContent>
            </Card>
          </TabsContent>
        </Tabs>
      </div>
    </div>
  )
}